<?php
namespace App\Helpers\Api;


use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Collection as BaseCollection;
use Watson\Rememberable\Rememberable;

trait CacheTrait
{
    use Rememberable;
//    static $expire_time = 300;

    public $rememberFor = 3600 * 24 * 30;

    /**
     * 如果方法是 find($id, $nocache)
     *
     * @param  string $method
     * @param  array $parameters
     * @return mixed
     */
    public static function __callStatic($method, $parameters)
    {
        $model = new static;
        if ($method == 'find') {
            $key = self::class . ":" . $parameters[0];
            return (new static)->cacheTags($key)->$method(...$parameters);
        }
        return $model->$method(...$parameters);
    }


    public static function deleteCachePk($key) {
        $model = new static;
        $key = self::class . ":" . $key;
        return $model->flushCache($key);
    }

    /**
    private static function getCacheKey($id)
    {
        $name = str_replace('\\', ':', __CLASS__);
        return "{$name}:{$id}";
    }

    private static function clearCache($id){
        Redis::del(self::getCacheKey($id));
    }


    public function save(array $options = []){
        $res = parent::save($options);
        static::clearCache($this[$this->primaryKey]);
        return $res;
    }

    public static function destroy($ids) {
        $res = parent::destroy($ids);
        if ($ids instanceof BaseCollection) {
            $ids = $ids->all();
        }
        $ids = is_array($ids) ? $ids : func_get_args();
        foreach ($ids as $id)
            static::clearCache($id);
        return $res;
    }
    **/




}